﻿namespace IBTrader.Indicator.Oscillator
{
    using IBTrader.Indicator.Average;
    using IBTrader.Modules.Read;
    using IBTrader.Charts;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class ChaikinOscillator : BaseUpDown
    {
        private bool? last = null;
        private readonly double offset;
        private readonly List<EMA> ema;
        private Line line1 = null, line2;
        public ChaikinOscillator(Worker worker, int interval1 = 3, int interval2 = 10, double offset = .005) : base(worker, 1, 2)
        {
            this.offset = offset;
            ema = new[] { interval1, interval2 }.Select(i => new EMA(worker, i)).ToList();
            ema[0].Hit += (_, line) => line1 = line;
            ema[1].Hit += (_, line) => { line2 = line; OnHit(line, line1.Price - line2.Price); };
        }
        public override void Add(object sender, Line line)
        {
            ema.ForEach(e => e.Add(sender, line));
            Test(line1, line2, line);
        }
        internal void Test(Line la, Line lb, Line line)
        {
            if (la != null && lb != null)
            {
                var p = la.Price - lb.Price;
                if (Math.Abs(p) > offset)
                {
                    bool up = p > offset ? true : false;
                    if (up != last)
                    {
                        if (up)
                            OnUp(line);
                        else
                            OnDown(line);
                    }
                    last = up;
                }
            }
        }
    }
}